import { Request, Response, NextFunction } from 'express';
import logger from '../utils/logger';

/**
 * 请求日志中间件
 */
export const requestLogger = (req: Request, res: Response, next: NextFunction) => {
  const start = Date.now();
  
  res.on('finish', () => {
    const duration = Date.now() - start;
    const logData = {
      method: req.method,
      url: req.originalUrl,
      status: res.statusCode,
      duration: `${duration}ms`,
      ip: req.ip,
      userAgent: req.get('User-Agent')
    };
    
    if (res.statusCode >= 400) {
      logger.warn('HTTP请求警告', logData);
    } else {
      logger.info('HTTP请求完成', logData);
    }
  });
  
  next();
};

/**
 * 错误日志中间件
 */
export const errorLogger = (error: Error, req: Request, res: Response, next: NextFunction) => {
  logger.error('应用错误', {
    error: error.message,
    stack: error.stack,
    url: req.originalUrl,
    method: req.method,
    ip: req.ip,
    body: req.body,
    params: req.params,
    query: req.query
  });
  
  next(error);
};